#Requires -Modules @{ ModuleName="Az.Accounts"; ModuleVersion="2.2.0" }
<#  
.SYNOPSIS  
  This script will create new Qualys or Rapid7 vulnerability assessment (VA) solution in Azure Security Center (ASC).
     
.DESCRIPTION  
  ASC contract VA solution is provided as an integration service. This script uses REST API to create a new Security Solution in ASC.
  The solution requires a license and a key provided by the 3rd party VA provider: Qualys or Rapid7
  Note that only one solution can be created per license. An attempt to create another solution using the same name/license/key will fail.
  You will need to make sure to set the current Azure context to your current subscription. Azure Security Center will automatically decide on a location to save some of your data per subscription.
  The script below will query that location and use it within the REST URI. You can set your Azure context by running the command set-azcontext -subscriptionId <yourSubscriptionID>.
  
.PARAMETER SubscriptionId
  [mandatory] 
  The subscriptionID of the Azure Subscription that contains the resources you want to analyze

.PARAMETER ResourceGroupName
  [mandatory] 
  It can be any EXISTING resource group, using the ASC default "DefaultResourceGroup-XXX" is one option.
  Note: Since the ASC VA solution is not an Azure resource it will not be listed under the resource group, but still it is attached to it.

.PARAMETER vaSolutionName
  [mandatory] 
  The name of the new solution

.PARAMETER vaType
  [mandatory] 
  Qualys or Rapid7

.PARAMETER licenseCode
  [mandatory] 
  VA provided license string or Base64 represantation of Rapid7 zip file
  
.PARAMETER publicKey
[mandatory] 
  VA provided key

.PARAMETER autoUpdate
  Turn solution Auto deploy. 
  When On every new VM to the subscription will be automatically attempted to link to the solution.
  Default: False  
  
.EXAMPLE
.\New-ASCVASolution.ps1 -subscriptionId <Subscription ID> -resourceGroupName <RG Name> -vaSolutionName <New solution name> -vaType <Qualys/Rapid7> -autoUpdate <true/false> -licenseCode <License acquired by the vendor> -publicKey <Key provided by the vendor>

.EXAMPLE
.\New-ASCVASolution.ps1 -subscriptionId f4f71b69-dcab-4ce6-8e6f-ea2e92223d3b -resourceGroupName DefaultResourceGroup-WEU -vaSolutionName QualysVaf4f -vaType Qualys -autoUpdate false -licenseCode 'eyJjaWQilkjOiJkZDghkjkjTMzLWM4NTSksjk342OS1mZWM1N2Q3ZGU5MjgiLCJhaWQiOiIyMmM5NDg3MS1lNTVkLTQ1OGItYjhlMC03OTRhMmM3YWM1ZGQiLCJwd3NVcmwiOiJodHRwczovL3FhZ3B1YmxpYy1wMDEuaW50LnF1YWx5cy5jb20vQ2xvdWRBZ2VudC8iLCJwd3NQb3rockjoiAWQzIn0=' -publicKey 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQgdQCOiOLXjOywMfLZIBGPZLwSocf1Q64BEFQS9OHFEmanBl1nkJhZDrZ4YD5qIx3fThYbAx1Rde2iYV1ze/wDlX4cIvFAyXuN1BSv4qeIlBl6vWXEBZpUU17bOdJOUGolzEzNBhtxi/elEZLghq9Chmah82me/okGMIhJJsCiTtglVQIDAQAB'

.NOTES
   AUTHOR: Eli Sagie - ASC EEE 
   LASTEDIT: March 11, 2021 2.10
    - 2.10 change log: Changing the solution destination location to reside on the Resource-Group location

.LINK
    This script posted to and discussed at the following locations:
    https://github.com/Azure/Azure-Security-Center/tree/master/Powershell%20scripts
#>

# Prerequisites
# Install-module Az
# Install-module Az.security


param (
	[Parameter(Mandatory = $true)]
	[string]$subscriptionId,
	
	[Parameter(Mandatory = $true)]
	[string]$resourceGroupName,
	
	[Parameter(Mandatory = $true)]
	[string]$vaSolutionName,
	
	[Parameter(Mandatory = $true)]
	[ValidateSet('Qualys','Rapid7')]
	[string]$vaType,

	[ValidateSet('true','false')]
	[string]$autoUpdate = "false",	
	
	[Parameter(Mandatory = $true)]
	# If Rapid7 provide the ConfigZipFileInBase64 
	[string]$licenseCode,
	
	[Parameter(Mandatory = $true)]
	[string]$publicKey
	)

#Validations
 if (!(Get-InstalledModule -Name Az) -AND (!(Get-InstalledModule -Name Az.Security)))
	{
		write-host "Az and Az.Security modules are required.`nOn elevated powershell console run: 'Install-module Az' then 'Install-module Az.Security' and try again"
		return
	}

if ((Get-AzContext).Subscription.Id -ne $subscriptionId)
{
	try 
	{
		Write-Host "Selecting $subscriptionId as the context for the script"
		Set-AzContext -SubscriptionId $subscriptionId -ErrorAction Stop
	} 
	catch 
	{
		"Make sure to login and select the destination subscription $subscriptionId"
		return
	}
}

#Access token
$token = (Get-AzAccessToken).token

#Variable declaration
	$requestHeader = @{
	  "Authorization" = "Bearer " + $token
	  "Content-Type" = "application/json"
	}

	$loc = (Get-AzSecurityLocation).Name
	$solutionLocation = (Get-AzResourceGroup -Name $($resourceGroupName)).Location

	if ($vaType -eq "Qualys") {$vaTemplate = "qualys.qualysAgent"}
	if ($vaType -eq "Rapid7") {$vaTemplate = "rapid7.insightplatform"}

$jsonBody = @"
{
    Properties: {
        Location: "$($solutionLocation)",
        Template: "$($vaTemplate)",
        ProvisioningParameters: 
			"{\"licenseCode\":\"$($licenseCode)\",\"publicKey\":\"$($publicKey)\",\"autoUpdate\":$($autoUpdate)}"
    }
}
"@

#Invoke
	$restUri = "https://management.azure.com/subscriptions/" + $subscriptionId + "/resourceGroups/" + $resourceGroupName + "/providers/Microsoft.Security/locations/" + $loc + "/securitySolutions/" + $vaSolutionName + "?api-version=2015-06-01-preview"
	Invoke-RestMethod -Uri $restUri -Method PUT -Headers $requestHeader -Body $jsonBody

# Delete solution
# Comment-out the above PUT invocation and uncomment this invoke command
#Invoke-RestMethod -Uri $restUri -Method DELETE -Headers $requestHeader
